package com.qyhl.module_practice.center;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.qyhl.module_practice.R;
import com.qyhl.module_practice.R2;
import com.qyhl.module_practice.score.mine.PracticeScoreMineContract;
import com.qyhl.module_practice.score.mine.PracticeScoreMinePresenter;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.UpTokenBean;
import com.qyhl.webtv.commonlib.entity.act.UploadBean;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeVolunteerDetailBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.qiniu.QiniuUpload;
import com.qyhl.webtv.commonlib.utils.qiniu.UploadResultListener;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.weavey.loading.lib.LoadingLayout;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.PRACTICE_CENTER)
public class PracticeCenterActivity extends BaseActivity implements PracticeScoreMineContract.PracticeScoreMineView {
    @BindView(R2.id.head_icon)
    ImageView headIcon;
    @BindView(R2.id.name)
    TextView name;
    @BindView(R2.id.captain_tag)
    ImageView captainTag;
    @BindView(R2.id.vol_tag)
    ImageView volTag;
    @BindView(R2.id.vol_level_tag)
    ImageView volLvTag;
    @BindView(R2.id.act_num)
    TextView actNum;
    @BindView(R2.id.service_duration)
    TextView serviceDuration;
    @BindView(R2.id.score_rank)
    TextView scoreRank;
    @BindView(R2.id.vol_info_layout)
    RelativeLayout volInfoLayout;
    @BindView(R2.id.score)
    TextView score;
    @BindView(R2.id.score_layout)
    LinearLayout scoreLayout;
    @BindView(R2.id.bottom_layout)
    RelativeLayout bottomLayout;
    @BindView(R2.id.divider1)
    View divider1;
    @BindView(R2.id.score_act)
    TextView scoreAct;
    @BindView(R2.id.divider2)
    View divider2;
    @BindView(R2.id.score_upload)
    TextView scoreUpload;
    @BindView(R2.id.divider3)
    View divider3;
    @BindView(R2.id.score_exchange)
    TextView scoreExchange;
    @BindView(R2.id.divider35)
    View divider35;
    @BindView(R2.id.score_integral)
    TextView scoreIntegral;
    @BindView(R2.id.score_year)
    TextView scoreYear;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.my_order)
    TextView myOrder;

    private String userName;

    private String volId;

    private int volStatus;

    private String instId;

    private PracticeVolunteerDetailBean mBean;

    private boolean isVolunteer;

    private PracticeScoreMinePresenter mPresenter;


    /**
     * 图片数据
     */
    private List<LocalMedia> selectedList = new ArrayList<>();


    @Override
    protected int getContentView() {
        return R.layout.practice_activity_center;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new PracticeScoreMinePresenter(this);
        BusFactory.getBus().register(this);
        userName = getIntent().getStringExtra("userName");
        volId = getIntent().getStringExtra("id");
        volStatus = getIntent().getIntExtra("status", 0);
        instId = getIntent().getStringExtra("instId");
        String titleName = getIntent().getStringExtra("title");

        if (StringUtils.isEmpty(titleName)) {
            title.setText("个人中心");
        } else {
            title.setText(titleName);
        }
        setCenter();

    }

    private void setCenter() {
        if (CommonUtils.getInstance().getSite() == 140) {
            myOrder.setVisibility(View.GONE);

        } else {
            myOrder.setVisibility(View.VISIBLE);
        }
        if (volStatus == 1) {
            loadMask.setStatus(LoadingLayout.Loading);
            isVolunteer = true;
            volInfoLayout.setVisibility(View.VISIBLE);
            scoreLayout.setVisibility(View.GONE);

            divider1.setVisibility(View.VISIBLE);
            divider2.setVisibility(View.VISIBLE);
            divider3.setVisibility(View.VISIBLE);
            divider35.setVisibility(View.VISIBLE);

            scoreAct.setVisibility(View.VISIBLE);
            scoreUpload.setVisibility(View.VISIBLE);
            if (CommonUtils.getInstance().getSite() == 140) {
                scoreExchange.setVisibility(View.GONE);

            } else {
                scoreExchange.setVisibility(View.VISIBLE);
            }


            bottomLayout.setVisibility(View.GONE);
            volTag.setVisibility(View.VISIBLE);
            volTag.setImageResource(R.drawable.practice_score_volunteer_tag_icon);

            mPresenter.getDetail(volId);

        } else {
            loadMask.setStatus(LoadingLayout.Success);
            isVolunteer = false;
            if (volStatus == 2) {
                bottomLayout.setVisibility(View.GONE);
                volTag.setImageResource(R.drawable.practice_score_judge_tag_icon);
            } else {
                volTag.setImageResource(R.drawable.practice_score_become_volunteer_tag_icon);
                bottomLayout.setVisibility(View.VISIBLE);
            }

            volLvTag.setImageResource(R.drawable.practice_volunteer_level_zero_icon);

            volInfoLayout.setVisibility(View.GONE);
            scoreLayout.setVisibility(View.GONE);

            divider1.setVisibility(View.GONE);
            divider2.setVisibility(View.GONE);
            divider3.setVisibility(View.GONE);
            divider35.setVisibility(View.GONE);

            scoreAct.setVisibility(View.GONE);
            scoreUpload.setVisibility(View.GONE);
            scoreExchange.setVisibility(View.GONE);
            scoreIntegral.setVisibility(View.GONE);

            String nickname = CommonUtils.getInstance().getNickName();
            String head = CommonUtils.getInstance().getUserLogo();
            Glide.with(this)
                    .load(head)
                    .apply(new RequestOptions().placeholder(R.drawable.comment_head_default).error(R.drawable.comment_head_default).circleCrop())
                    .into(headIcon);

            name.setText(nickname);

        }
    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                mPresenter.getDetail(volId);
            }
        });
    }


    @OnClick({R2.id.back_btn, R2.id.become_btn, R2.id.shop_btn, R2.id.score_service_team, R2.id.score_act, R2.id.score_upload, R2.id.score_exchange, R2.id.score_integral,
            R2.id.head_icon, R2.id.rank_layout, R2.id.vol_level_tag, R2.id.act_layout, R2.id.time_layout, R2.id.my_order})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.back_btn) {
            finish();
        } else if (id == R.id.become_btn) {

            Bundle bundle = new Bundle();
            bundle.putBoolean("isVolunteer", true);
            bundle.putString("instId", instId);
            RouterManager.router(ARouterPathConstant.PRACTICE_VOLUNTEER_SIGN, bundle);

        } else if (id == R.id.shop_btn) {

            CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                @Override
                public void login(boolean isLogin) {
                    if (isLogin) {


                        Bundle bundle = new Bundle();
                        bundle.putString("id", volId);
                        bundle.putString("userName", userName);
                        RouterManager.router(ARouterPathConstant.PRACTICE_SCORE_SHOP, bundle);
                    } else {
                        RouterManager.routerLogin(PracticeCenterActivity.this, 0);
                    }
                }

                @Override
                public void error(String s) {

                }
            });

        } else if (id == R.id.my_order) {
            Bundle bundle = new Bundle();
            bundle.putString("id", volId);
            bundle.putString("userName", userName);
            bundle.putBoolean("isVolunteer", volStatus == 1);
            bundle.putString("instId", instId);
            RouterManager.router(ARouterPathConstant.PRACTICE_ORDER_MINE, bundle);
        } else if (id == R.id.score_service_team) {
            if (mBean != null && mBean.getOrgs() != null && mBean.getOrgs().size() > 0) {
                if (mBean.getOrgs().size() == 1) {

                    Bundle bundle = new Bundle();
                    bundle.putString("volId", volId);
                    bundle.putString("instId", instId);
                    bundle.putString("title", "我的服务队");
                    bundle.putString("orgId", mBean.getOrgs().get(0).getId() + "");
                    bundle.putBoolean("isMine", true);
                    RouterManager.router(ARouterPathConstant.PRACTICE_TEAM_DETAIL, bundle);

                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString("volId", volId);
                    bundle.putString("instId", instId);
                    bundle.putString("title", "我的服务队");
                    bundle.putInt("status", volStatus);
                    bundle.putBoolean("isMine", true);
                    RouterManager.router(ARouterPathConstant.PRACTICE_TEAM_LIST, bundle);


                }
            } else {
                showToast("您尚未加入任何服务队!");
            }
        } else if (id == R.id.score_act) {

            Bundle bundle = new Bundle();
            bundle.putString("id", volId);
            bundle.putString("userName", userName);
            bundle.putBoolean("isVolunteer", isVolunteer);
            bundle.putString("instId", instId);
            RouterManager.router(ARouterPathConstant.PRACTICE_SCORE_MY_ACT, bundle);

        } else if (id == R.id.score_upload) {

            Bundle bundle = new Bundle();
            bundle.putString("volId", volId);
            bundle.putString("userName", userName);
            bundle.putString("actId", "");
            RouterManager.router(ARouterPathConstant.PRACTICE_APPLY, bundle);

        } else if (id == R.id.score_exchange) {

            Bundle bundle = new Bundle();
            bundle.putString("id", volId);
            RouterManager.router(ARouterPathConstant.PRACTICE_SCORE_MY_SHOP, bundle);
        } else if (id == R.id.score_integral) {
            Bundle bundle = new Bundle();
            bundle.putString("id", volId);
            RouterManager.router(ARouterPathConstant.PRACTICE_SCORE_BILL, bundle);
        } else if (id == R.id.head_icon) {
            if (volStatus == 1) {
                PictureSelector.create(PracticeCenterActivity.this)
                        .openGallery(PictureMimeType.ofImage())//仅图片
                        .imageSpanCount(4)//每行显示4张
                        .maxSelectNum(1)
                        .selectionMode(PictureConfig.SINGLE)//单选
                        .isCamera(true)//允许使用相机
                        .previewImage(true)//允许预览图片
                        .isZoomAnim(true)
                        .circleDimmedLayer(false)//圆形裁剪
                        .cropWH(80, 80)
                        .withAspectRatio(1, 1)
                        .freeStyleCropEnabled(true)
                        .enableCrop(true)
                        .compress(true)
                        .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                        .showCropGrid(true)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                        .minimumCompressSize(100)// 小于100kb的图片不压缩
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }
        } else if (id == R.id.rank_layout) {
            Bundle bundle = new Bundle();
            bundle.putInt("type", 3);
            bundle.putString("id", volId);
            RouterManager.router(ARouterPathConstant.PRACTICE_SCORE_RANK, bundle);
        } else if (id == R.id.act_layout) {

            Bundle bundle = new Bundle();
            bundle.putInt("type", 2);
            bundle.putInt("id", Integer.parseInt(volId));
            RouterManager.router(ARouterPathConstant.PRACTICE_SCORE_RANK, bundle);
        } else if (id == R.id.time_layout) {
            Bundle bundle = new Bundle();
            bundle.putInt("type", 1);
            bundle.putInt("id", Integer.parseInt(volId));
            RouterManager.router(ARouterPathConstant.PRACTICE_SCORE_RANK, bundle);
        } else if (id == R.id.vol_level_tag) {
            if (mBean != null) {
                Bundle bundle = new Bundle();
                bundle.putInt("duration", mBean.getServiceTimes());
                bundle.putInt("level", mBean.getLevel());
                RouterManager.router(ARouterPathConstant.PRACTICE_LEVEL, bundle);
            } else {
                Bundle bundle = new Bundle();
                bundle.putInt("duration", 0);
                bundle.putInt("level", 0);
                RouterManager.router(ARouterPathConstant.PRACTICE_LEVEL, bundle);
            }
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void setDetail(PracticeVolunteerDetailBean bean) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        mBean = bean;

        Glide.with(this)
                .load(bean.getLogo())
                .apply(new RequestOptions().placeholder(R.drawable.comment_head_default).error(R.drawable.comment_head_default).circleCrop())
                .into(headIcon);

        name.setText(bean.getName());

        scoreYear.setText(mBean.getAnnualScore() + "");

        scoreRank.setText(mBean.getTotalScore() + "");

        serviceDuration.setText(DateUtils.PracticeServiceTimeFormat(mBean.getServiceTimes()));

        switch (mBean.getLevel()) {
            case 0:
                volLvTag.setImageResource(R.drawable.practice_volunteer_level_zero_icon);
                break;
            case 1:
                volLvTag.setImageResource(R.drawable.practice_volunteer_level_one_icon);
                break;
            case 2:
                volLvTag.setImageResource(R.drawable.practice_volunteer_level_two_icon);
                break;
            case 3:
                volLvTag.setImageResource(R.drawable.practice_volunteer_level_three_icon);
                break;
            case 4:
                volLvTag.setImageResource(R.drawable.practice_volunteer_level_four_icon);
                break;
            case 5:
                volLvTag.setImageResource(R.drawable.practice_volunteer_level_five_icon);
                break;
            default:
                volLvTag.setImageResource(R.drawable.practice_volunteer_level_five_icon);
                break;
        }

        actNum.setText(mBean.getServiceNums() + "");


        if (StringUtils.isNotEmpty(bean.getRole()) && bean.getRole().equals("CAPTAIN")) {
            captainTag.setVisibility(View.VISIBLE);
        } else {
            captainTag.setVisibility(View.GONE);
        }
    }

    @Override
    public void setError(String msg) {
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setReloadButtonText("点击重试~");
        if (!NetUtil.isNetworkAvalible(this)) {
            loadMask.setErrorImage(R.drawable.error_network);
            loadMask.setErrorText("网络异常，请检查您的网络！");
        } else if (msg.contains("暂无")) {
            loadMask.setErrorImage(R.drawable.empty_content);
            loadMask.setErrorText(msg);
        } else {
            loadMask.setErrorImage(R.drawable.error_content);
            loadMask.setErrorText(msg);
        }
    }

    @Override
    public void getTokenSuccess(UpTokenBean data, boolean isUpload) {
        if (selectedList == null || selectedList.size() < 1) {
            showToast("头像出错！");
            dismissLoading();
        }

        if (data == null) {
            mPresenter.getToken(true);
            return;
        }

        List<UploadBean> uploadBeans = new ArrayList<UploadBean>();
        for (int i = 0; i < selectedList.size(); i++) {
            LocalMedia image = selectedList.get(i);
            UploadBean videoCoverBean = new UploadBean();
            videoCoverBean.setType(2);
            videoCoverBean.setPath(image.getCompressPath());
            videoCoverBean.setPostion(0);
            uploadBeans.add(videoCoverBean);
        }

        QiniuUpload.getQiniuUpload().UploadFiles(uploadBeans, data.getUptoken(), data.getPrefix(), new UploadResultListener() {
            @Override
            public void uplaodError() {
                dismissLoading();
                showToast("上传头像出错");
            }

            @Override
            public void uploadSuccess(List<UploadBean> files) {
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < files.size(); i++) {
                    if (i == files.size() - 1) {
                        stringBuilder.append(files.get(i).getUrl());
                    } else {
                        stringBuilder.append(files.get(i).getUrl()).append(",");
                    }
                }

                mPresenter.uploadHead(volId, stringBuilder.toString());

            }

            @Override
            public void uploadPre(double percent) {

            }
        });


    }

    @Override
    public void getTokenError(boolean isUpload) {
        if (isUpload) {
            dismissLoading();
            showToast("上传失败！");
        }
    }

    @Override
    public void uploadSuccess(String msg) {
        dismissLoading();
        showToast(msg);
        mPresenter.getDetail(volId);
    }

    @Override
    public void uploadError(String msg) {
        dismissLoading();
        showToast(msg);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(Event.PracticeCenterRefresh event) {
        if (event != null) {
            if (event.getType() == 0) {
                volStatus = 2;
                setCenter();
            } else {
                mPresenter.getDetail(volId);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PictureConfig.CHOOSE_REQUEST) {// 图片选择结果回调
            List<LocalMedia> resultList = PictureSelector.obtainMultipleResult(data);
            // 例如 LocalMedia 里面返回三种path
            // 1.media.getPath(); 为原图path
            // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
            // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
            // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
            if (resultList != null && resultList.size() > 0) {
                showLoading();
                selectedList.clear();
                selectedList.addAll(resultList);
                mPresenter.getToken(true);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BusFactory.getBus().unregister(this);
    }


    @Override
    protected void onResume() {
        super.onResume();
        ActionLogUtils.getInstance().onResume(this, ActionConstant.PRACTICE_CENTER);
    }

    @Override
    protected void onPause() {
        super.onPause();
        ActionLogUtils.getInstance().onPause(this, ActionConstant.PRACTICE_CENTER);
    }

}
